package it.ap.sa.acqua.hibernate.custom.function;

import java.util.List;

import org.hibernate.QueryException;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.type.Type;

import it.ap.sa.core.utils.ListUtils;

/**
 * @author Alessandro Paolillo
 */
public abstract class TplSqlConversionFunction implements SQLFunction {

	private String sqlFunction;
	private Type returnType;
	/**
	 * Costruttore
	 * @param sqlFunction. Nome function sql
	 * @param returnType. Tipo ritorno
	 */
	public TplSqlConversionFunction(String sqlFunction, Type returnType) {
		this.sqlFunction = sqlFunction;
		this.returnType  = returnType;
	}

	/**
	 * @author Alessandro Paolillo
	 */
	@Override
	public boolean hasArguments() {
		return true;
	}

	/**
	 * @author Alessandro Paolillo
	 */
	@Override
	public boolean hasParenthesesIfNoArguments() {
		return false;
	}

	/**
	 * @author Alessandro Paolillo
	 */
	@Override
	public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
		return this.returnType;
	}

	/**
	 * @author Alessandro Paolillo
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory)
	throws QueryException {
		StringBuilder result = new StringBuilder();
		String        sep    = "";
		
		result.append(this.sqlFunction)
		      .append("(")
		      ;
		if(ListUtils.listIsNotEmpty(arguments)){
			for(Object argument : arguments){
				result.append(sep)
			          .append(argument)
			      ;
				sep = ",";
			}
		}
		
		
		result.append(")");
		
		return result.toString();
		
	}

	/**
	 * @return the sqlFunction. Il nomde della function sql
	 */
	public String getSqlFunction() {
		return sqlFunction;
	}

}
